﻿using UnityEngine;
using XLua;
using Framework.AssetsManager;
using Framework;
using System;

public class Mainloop : MonoBehaviour {
    #region singleton
    static Mainloop _instance;

    public static Mainloop Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject mainLoopGO = Instantiate(Resources.Load("Mainloop")) as GameObject;
                mainLoopGO.name = "Mainloop";
                DontDestroyOnLoad(mainLoopGO);
                _instance = mainLoopGO.GetComponent<Mainloop>();
                
            }
            return _instance;
        }
    }
    #endregion

    public string AppVersion = "";
    public LuaEnv luaenv = null;

    #region Quality
    public Action onQualityChange;
    public int QualityLevel
    {
        get
        {
            if(PlayerPrefs.HasKey("QualityLevel") == false)
            {
                PlayerPrefs.SetInt("QualityLevel", 3);
                PlayerPrefs.Save();
                SetQuality();
            }
            return PlayerPrefs.GetInt("QualityLevel");
        }

        set
        {
            PlayerPrefs.SetInt("QualityLevel", value);
            PlayerPrefs.Save();
            SetQuality();
        }
    }

    public void SetQuality()
    {
        int quality = PlayerPrefs.GetInt("QualityLevel");
        QualitySettings.SetQualityLevel(quality - 1);
        if (onQualityChange != null)
            onQualityChange();
    }
    #endregion

    public Ctrl ctrl { private set; get; }

    #region Unity
    private void Start()
    {
        MessageSystem messageSystem = MessageSystem.Instance;

        ctrl = new Ctrl();
        ctrl.changeProc(ProcType.PROC_UPDATE);
    }

    void Update ()
    {
        ABCacheTimer.Instance.Process();
        CoroutineDecorator.Instance.OnUpdate(Time.deltaTime);

        if (luaenv != null)
            luaenv.Tick();

        ctrl.Update();
    }

    public Action onFixedUpdate;

    private void FixedUpdate()
    {
        if (onFixedUpdate != null)
            onFixedUpdate();
    }

    private void OnApplicationQuit()
    {
        Network.NetManager.Instance.Destroy(); 
    }
    #endregion

    public void ShowNoNetworkTips()
    {

    }
}
